package com.huilian.iotbox.admin.wap.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huilian.iotbox.admin.wap.dao.*;
import com.huilian.iotbox.admin.wap.service.*;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.dto.*;
import com.huilian.iotbox.data.enums.*;
import com.huilian.iotbox.data.po.*;
import com.huilian.iotbox.data.service.SystemConfigService;
import com.huilian.iotbox.data.service.UploadService;
import com.huilian.iotbox.data.utils.DateTimeUtils;
import com.huilian.iotbox.data.utils.SnowflakeIdWorker;
import com.huilian.iotbox.data.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommodityServiceImpl implements CommodityService {
    @Resource
    private CommodityDao commodityDao;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Resource
    private CommodityStockService commodityStockService;
    @Resource
    private CommodityGroupService commodityGroupService;
    @Resource
    private CommodityInfoCommonDao commodityInfoCommonDao;
    @Resource
    private CommodityStoreUpDownDao commodityStoreUpDownDao;
    @Resource
    private CommodityStoreUpDownService commodityStoreUpDownService;
    @Resource
    private CommodityProjectRelevanceService commodityProjectRelevanceService;
    @Resource
    private CommodityPurchaseRestrictionDao commodityPurchaseRestrictionDao;
    @Resource
    private CommodityDetailService commodityDetailService;
    @Override
    public List<CommodityVo> findByStoreIdAndUserIdCommodity(CommodityDto commodityDto) {
        commodityDto.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
        commodityDto.setType(CommodityTypeEnum.REGULAR.getCode());
        List<CommodityVo> commodityVoList = commodityDao.findByStoreIdAndUserIdCommodity(commodityDto);
        SystemConfig systemConfig = systemConfigService.findOneSystemConfigById(1);
        // 设置默认 计量单位
        for (CommodityVo commodityVo : commodityVoList) {
            CommodityPurchaseRestrictionRecordDto cprrd = new CommodityPurchaseRestrictionRecordDto();
            cprrd.setStatus(CommodityPurchaseRestrictionStatusEnum.NORMAL.getCode());
            cprrd.setCommodityStoreUpDownId(commodityVo.getCommodityStoreUpDownId());
            cprrd.setUserId(commodityDto.getUserId());
            CommodityPurchaseRestrictionVo oneCommodityPurchaseRestriction = commodityPurchaseRestrictionDao.getOneCommodityPurchaseRestriction(cprrd);
            if(!StringUtils.isEmpty(oneCommodityPurchaseRestriction)){
                commodityVo.setPurchaseLimit(oneCommodityPurchaseRestriction.getPurchaseLimit());
                commodityVo.setCprStatus(oneCommodityPurchaseRestriction.getCprStatus());
                commodityVo.setEndTime(oneCommodityPurchaseRestriction.getEndTime());
                commodityVo.setCprId(oneCommodityPurchaseRestriction.getCprId());
                commodityVo.setOriginalPrice(oneCommodityPurchaseRestriction.getOriginalPrice());
            }
            if (StringUtils.isEmpty(commodityVo.getUnit())) {
                if (StringUtils.isEmpty(commodityVo.getMeasuringUnit())) {
                    commodityVo.setUnit(systemConfig.getDefaultMeasuringUnit());
                } else {
                    commodityVo.setUnit(commodityVo.getMeasuringUnit());
                }
            }
        }
        return commodityVoList;
    }

    @Override
    public List<CommodityVo> findByStoreIdAndUserIdCommodityV2(CommodityDto commodityDto) {
        commodityDto.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
        commodityDto.setType(CommodityTypeEnum.RECHARGE_BALANCE.getCode());
        List<CommodityVo> commodityVoList = commodityDao.findByStoreIdAndUserIdCommodity(commodityDto);
        return commodityVoList;
    }



    /**
     * 删除余额套餐
     *
     * @param commodityDto
     * @return
     */
    @Override
    @Transactional
    public ServerResponse deleteBalancePackage(CommodityDto commodityDto) {
        CommodityVo commodityVo = commodityDao.queryById(commodityDto.getId());
        List<CommodityVo> commodityVoList  = this.findByStoreIdAndUserIdCommodityV2(commodityDto);
        //逻辑删除套餐表
        // int resultCommodity = commodityDao.deletePackage(commodityDto);
        //逻辑删除门店上下架表
        CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
        commodityStoreUpDownDto.setId(commodityDto.getCsudId());
        commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.OFF_SHELF.getCode());
        commodityStoreUpDownDto.setUserInfo(commodityDto.getUserInfo());
        int resultCommodityStoreUpDown = commodityStoreUpDownDao.update(commodityStoreUpDownDto);
        for (CommodityVo commodityVo1 : commodityVoList) {
            if (commodityVo1.getSort() > commodityVo.getSort()) {
                commodityVo1.setSort(commodityVo1.getSort() - 1);
                CommodityDto packageDto = new CommodityDto();
                BeanUtils.copyProperties(commodityVo1, packageDto);
                commodityDao.updatePackage(packageDto);
            }
        }
        if (resultCommodityStoreUpDown > 0) {
            return ServerResponse.createBySuccess("删除成功");
        } else {
            return ServerResponse.createByError("删除失败");
        }
    }

    /**
     * 编辑套餐
     */
    @Override
    public ServerResponse editPackage(CommodityDto commodityDto) {
        if (StringUtils.isEmpty(commodityDto.getMerchantStoreId())) {
            return ServerResponse.createByErrorMessage("场地ID不能为空");
        }
        if (StringUtils.isEmpty(commodityDto.getRetailPrice())) {
            return ServerResponse.createByErrorMessage("售价不能为空");
        }
        if (StringUtils.isEmpty(commodityDto.getRechargeCoin()) || StringUtils.isEmpty(commodityDto.getGiveCoin())) {
            return ServerResponse.createByErrorMessage("套餐填写有误，请检查套餐设置");
        }

        BigDecimal amount = new BigDecimal(0);
        if (commodityDto.getRechargeCoin() <= 0 || commodityDto.getGiveCoin() < 0
                || commodityDto.getRetailPrice().compareTo(amount) <= 0) {
            return ServerResponse.createByErrorMessage("套餐填写有误，请检查套餐设置");
        }

        // 判断游戏币单个币的价值不能低于系统的最低水平
        int coins = commodityDto.getRechargeCoin() + commodityDto.getGiveCoin();
        BigDecimal price = commodityDto.getRetailPrice().divide(new BigDecimal(coins), 2, RoundingMode.HALF_UP);
        SystemConfig systemConfig = systemConfigService.findOneSystemConfigById(1);
        if (price.compareTo(systemConfig.getSalesPackageRatio()) < 0) {
            return ServerResponse.createByErrorMessage(String.format("单个游戏币不能低于%s元，请重新填写", systemConfig.getSalesPackageRatio()));
        }
        if (commodityDto.getRetailPrice().compareTo(systemConfig.getSalePackageMaximumPrice()) > 0) {
            return ServerResponse.createByErrorMessage(String.format("销售价不能超过%s元", systemConfig.getSalePackageMaximumPrice()));
        }

        BigDecimal retailPrice = commodityDto.getRetailPrice(); //用作后续发送用
        Integer count;
        if (!StringUtils.isEmpty(commodityDto.getId())) {
            // 检查游戏币商品是否存在
            CommodityDto commodityCondition = new CommodityDto();
            commodityCondition.setId(commodityDto.getId());
            commodityCondition.setUserInfo(commodityDto.getUserInfo());
            Commodity commodity = commodityDao.findOneCommodityByIdAndPermission(commodityCondition);
            if (StringUtils.isEmpty(commodity)) {
                return ServerResponse.createByErrorMessage("游戏币套餐_1_不存在");
            }

            if (StringUtils.isEmpty(commodityDto.getCommodityStoreUpDownId())) {
                return ServerResponse.createByErrorMessage("游戏币套餐ID_2_不能为空");
            }
            // 检查游戏币商品上架ID是否存在
            CommodityStoreUpDownDto commodityStoreUpDownCondition = new CommodityStoreUpDownDto();
            commodityStoreUpDownCondition.setId(commodityDto.getCommodityStoreUpDownId());
            commodityStoreUpDownCondition.setUserInfo(commodityDto.getUserInfo());
            CommodityStoreUpDown commodityStoreUpDown = commodityStoreUpDownDao.findOneCommodityStoreUpDownByIdAndPermission(commodityStoreUpDownCondition);
            if (StringUtils.isEmpty(commodityStoreUpDown)) {
                return ServerResponse.createByErrorMessage("游戏币套餐_2_不存在");
            }

            CommodityStoreUpDownDto updateCommodityStoreUpDownDto = new CommodityStoreUpDownDto();
            if (!commodity.getIsDefault()) {
                // 非默认套餐可以修改套餐金额，默认套餐不可以修改价格
                updateCommodityStoreUpDownDto.setRetailPrice(retailPrice);
            }
            //修改 上下终端
            updateCommodityStoreUpDownDto.setUserInfo(commodityDto.getUserInfo());
            updateCommodityStoreUpDownDto.setId(commodityDto.getCommodityStoreUpDownId());
            if (StringUtils.isEmpty(commodityDto.getClientTerminal())) {
                updateCommodityStoreUpDownDto.setClientTerminal(false);
            } else {
                updateCommodityStoreUpDownDto.setClientTerminal(commodityDto.getClientTerminal());
            }
            if (StringUtils.isEmpty(commodityDto.getPosTerminal())) {
                updateCommodityStoreUpDownDto.setPosTerminal(false);
            } else {
                updateCommodityStoreUpDownDto.setPosTerminal(commodityDto.getPosTerminal());
            }
            commodityStoreUpDownDao.update(updateCommodityStoreUpDownDto);

            CommodityDto updateCommodityDto = new CommodityDto();
            updateCommodityDto.setId(commodityDto.getId());
            updateCommodityDto.setRechargeCoin(commodityDto.getRechargeCoin());
            updateCommodityDto.setGiveCoin(commodityDto.getGiveCoin());
            updateCommodityDto.setRecommend(commodityDto.getRecommend());
            updateCommodityDto.setHide(commodityDto.getHide());
            updateCommodityDto.setPosTerminal(commodityDto.getPosTerminal());
            updateCommodityDto.setUnit(commodityDto.getUnit());
            updateCommodityDto.setName(commodityDto.getGiveCoin() + commodityDto.getRechargeCoin() + "枚游戏币");
            if (StringUtils.isEmpty(commodityDto.getClientTerminal())) {
                updateCommodityDto.setClientTerminal(false);
            } else {
                updateCommodityDto.setClientTerminal(commodityDto.getClientTerminal());
            }
            if (StringUtils.isEmpty(commodityDto.getPosTerminal())) {
                updateCommodityDto.setPosTerminal(false);
            } else {
                updateCommodityDto.setPosTerminal(commodityDto.getPosTerminal());
            }

            count = commodityDao.updatePackage(updateCommodityDto);

            if (commodity.getHide() && !commodityDto.getHide()) {
                // 启用 改 隐藏
                CommodityDto commodityDtoCondition = new CommodityDto();
                commodityDtoCondition.setUserInfo(commodityDto.getUserInfo());
                commodityDtoCondition.setMerchantStoreId(commodityDto.getMerchantStoreId());
                commodityDtoCondition.setType(CommodityTypeEnum.REGULAR.getCode());
                List<Commodity> commodityList = commodityDao.findAllCommodityByIdAndPermission(commodityDtoCondition);

                List<Commodity> newCommodityList = commodityList.stream().sorted((item1, item2) -> {
                    return item1.getSort().compareTo(item2.getSort());
                }).collect(Collectors.toList());

                for (Commodity commodity1 : newCommodityList) {
                    CommodityDto updateCommodity = new CommodityDto();
                    updateCommodity.setId(commodity1.getId());
                    if (commodity.getSort().compareTo(commodity1.getSort()) == 0) {
                        // 隐藏套餐置最后
                        updateCommodity.setSort(newCommodityList.get(newCommodityList.size() - 1).getSort());
                        commodityDao.updatePackage(updateCommodity);
                        log.info("隐藏套餐sort:" + updateCommodity.getSort());
                    } else if (commodity.getSort().compareTo(commodity1.getSort()) < 0) {
                        // 被隐藏套餐后面的套餐 排序减1
                        updateCommodity.setSort(commodity1.getSort() - 1);
                        commodityDao.updatePackage(updateCommodity);
                        log.info("被隐藏套餐后面的套餐sort:" + updateCommodity.getSort());
                    }
                }
            }
        } else {
            // 查询是否存在【游戏币】分组，不存在就创建
            CommodityGroupDto groupDto = new CommodityGroupDto();
            //子账号登录的话，拿父级id
            if (commodityDto.getUserInfo().getRoleId().equals(RoleEnum.SUB_ACCOUNT.getRoleId())) {
                //子账号查询场地userId
                groupDto.setUserId(commodityDto.getUserInfo().getParentId());
            } else {
                groupDto.setUserId(commodityDto.getUserInfo().getId());
            }
            //查询有没有游戏币套餐分组，没有则新增游戏币套餐分组
            groupDto.setType(CommodityGroupTypeEnum.GAME_COIN.getCode());
            CommodityGroup commodityGroup = commodityGroupService.getOneCommodityGroupByUserIdAndType(groupDto);
            if (StringUtils.isEmpty(commodityGroup)) {
                commodityGroup = new CommodityGroup();
                commodityGroup.setUserId(groupDto.getUserId());
                commodityGroup.setName("游戏币套餐");
                commodityGroup.setType(CommodityGroupTypeEnum.GAME_COIN.getCode());
                commodityGroupService.insert(commodityGroup);
            }
            // 新增套餐商品
            Commodity newCommodity = new Commodity();
            newCommodity.setUserId(groupDto.getUserId());
            newCommodity.setCommodityGroupId(commodityGroup.getId());
            newCommodity.setType(CommodityTypeEnum.REGULAR.getCode());
            newCommodity.setRetailPrice(commodityDto.getRetailPrice());
            newCommodity.setName(commodityDto.getGiveCoin() + commodityDto.getRechargeCoin() + "枚游戏币");
            newCommodity.setRechargeCoin(commodityDto.getRechargeCoin());
            newCommodity.setGiveCoin(commodityDto.getGiveCoin());
            newCommodity.setSort(commodityDao.findMaxPackageRecommend(commodityDto) + 1);
            newCommodity.setRecommend(commodityDto.getRecommend());
            newCommodity.setHide(commodityDto.getHide());
            newCommodity.setPosTerminal(commodityDto.getPosTerminal());
            newCommodity.setClientTerminal(true);
            newCommodity.setUnit(commodityDto.getUnit());
            count = commodityDao.insert(newCommodity);
            // 将套餐商品上架
            CommodityStoreUpDownDto cupd = new CommodityStoreUpDownDto();
            cupd.setCommodityId(newCommodity.getId());
            cupd.setMerchantStoreId(commodityDto.getMerchantStoreId());
            cupd.setUserId(groupDto.getUserId());
            cupd.setRetailPrice(commodityDto.getRetailPrice());
            cupd.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
            cupd.setPosTerminal(commodityDto.getPosTerminal());
            cupd.setClientTerminal(true);
            commodityStoreUpDownDao.insert(cupd);
        }
        if (count > 0) {
            return ServerResponse.createBySuccess(commodityDto.getId());
        } else {
            return ServerResponse.createByErrorMessage("套餐保存失败");
        }
    }

    @Override
    public ServerResponse findByStatus(CommodityDto commodityDto) {
        List<CommodityVo> commodityVoList = commodityDao.findByStatus(commodityDto);
        Map<Long, CommodityVo> onSaleMap = new HashMap<>();
        Map<Long, CommodityVo> offSaleMap = new HashMap<>();

        for (CommodityVo commodity : commodityVoList) {
            if (commodity.getStatus() == null || commodity.getStatus() == 0) {
                if (!offSaleMap.containsKey(commodity.getId())) {
                    offSaleMap.put(commodity.getId(), commodity);
                }
            } else {
                if (!onSaleMap.containsKey(commodity.getId())) {
                    onSaleMap.put(commodity.getId(), commodity);
                }
            }
        }

        List<CommodityVo> returnList = new ArrayList<>();
        CommodityVo commodityVo1 = new CommodityVo();
        commodityVo1.setCommodityVoList(new ArrayList<>(onSaleMap.values()));
        commodityVo1.setName("已上架");
        returnList.add(commodityVo1);

        CommodityVo commodityVo2 = new CommodityVo();
        commodityVo2.setCommodityVoList(new ArrayList<>(offSaleMap.values()));
        commodityVo2.setName("已下架");
        returnList.add(commodityVo2);

        return ServerResponse.createBySuccess(returnList);
    }


    @Override
    public ServerResponse findMerchantStore(CommodityDto commodityDto) {
        List<CommodityVo> commodityVoList = commodityDao.findMerchantStore(commodityDto);
        return ServerResponse.createBySuccess(commodityVoList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse saveProduct(CommodityDto commodityDto) {
        if (commodityDto.getName().isEmpty()) {
            return ServerResponse.createByErrorMessage("缺少商品名称");
        }
        if (ObjectUtils.isEmpty(commodityDto.getCommodityGroupId())) {
            return ServerResponse.createByErrorMessage("未选择商品分组");
        }
        if (ObjectUtils.isEmpty(commodityDto.getRetailPrice())) {
            return ServerResponse.createByErrorMessage("缺少默认价格");
        }
        if (ObjectUtils.isEmpty(commodityDto.getRetailVIPPrice())) {
            return ServerResponse.createByErrorMessage("缺少会员价格");
        }
        if (StringUtils.isEmpty(commodityDto.getPosTerminal()) && StringUtils.isEmpty(commodityDto.getIntegralMallTerminal())) {
            return ServerResponse.createByErrorMessage("未选择上架终端_1");
        } else if (StringUtils.isEmpty(commodityDto.getPosTerminal()) && !commodityDto.getIntegralMallTerminal()) {
            return ServerResponse.createByErrorMessage("未选择上架终端_2");
        } else if (StringUtils.isEmpty(commodityDto.getIntegralMallTerminal()) && !commodityDto.getPosTerminal()) {
            return ServerResponse.createByErrorMessage("未选择上架终端_3");
        }
        //未传商品id 添加
        if (ObjectUtils.isEmpty(commodityDto.getId())) {
            //开启兑换 判断
            commodityDto.setOpenRecovery(this.isOpenRecovery(commodityDto));
            //开启回收 判断
            commodityDto.setOpenExchange(this.isOpenExchange(commodityDto));
            //插入commodity数据
            commodityDto.setHide(true);
            commodityDto.setType(CommodityTypeEnum.CURRENT.getCode());
            commodityDao.keepInsert(commodityDto);
            //没填写商品条码 生成条码
            if (commodityDto.getBarCode().isEmpty() && commodityDto.getBarCodeStatus()) {
                Long barCode = commodityDto.getId();
                // 补齐5位数，不足的前面用0填充
                String sb = commodityDto.getCommodityGroupId() + String.format("%05d", barCode);
                // 将拼接好的字符串赋值给商品的barCode属性
                commodityDto.setBarCode(sb);
                //更新barCode 商品条码
                commodityDao.updateCommodity(commodityDto);
            }
            //添加操作 商品详情图片
            CommodityDetailDto commodityDetailDto = new CommodityDetailDto();
            commodityDetailDto.setCommodityId(commodityDto.getId());
            commodityDetailDto.setFileName(commodityDto.getCommodityDetailFileName());
            commodityDetailService.insert(commodityDetailDto);
            //添加操作 上下架
            if (!ObjectUtils.isEmpty(commodityDto.getMerchantStoreIdList())) {
                for (Integer merchantStoreId : commodityDto.getMerchantStoreIdList()) {
                    CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
                    commodityStoreUpDownDto.setCommodityId(commodityDto.getId());
                    commodityStoreUpDownDto.setMerchantStoreId(merchantStoreId);
                    commodityStoreUpDownDto.setUserId(commodityDto.getUserId());
                    commodityStoreUpDownDto.setRetailPrice(commodityDto.getRetailPrice());
                    commodityStoreUpDownDto.setIncludeCoinSalesTurnover(commodityDto.getIncludeCoinSalesTurnover());
                    commodityStoreUpDownDto.setStrictInventoryManagement(commodityDto.getStrictInventoryManagement());
                    commodityStoreUpDownDto.setOpenExchange(commodityDto.getOpenExchange());
                    commodityStoreUpDownDto.setIntegralConversionPrice(commodityDto.getIntegralConversionPrice());
                    commodityStoreUpDownDto.setLotteryConversionPrice(commodityDto.getLotteryConversionPrice());
                    commodityStoreUpDownDto.setCoinConversionPrice(commodityDto.getCoinConversionPrice());
                    commodityStoreUpDownDto.setPosTerminal(commodityDto.getPosTerminal());
                    commodityStoreUpDownDto.setIntegralMallTerminal(commodityDto.getIntegralMallTerminal());
                    commodityStoreUpDownDto.setOpenRecovery(commodityDto.getOpenRecovery());
                    commodityStoreUpDownDto.setIsSelfMention(commodityDto.getIsSelfMention());
                    commodityStoreUpDownDto.setIsDirectMail(commodityDto.getIsDirectMail());
                    commodityStoreUpDownDto.setEverydayQuantityWrittenOff(commodityDto.getEverydayQuantityWrittenOff());
                    commodityStoreUpDownDto.setQuantityWrittenOff(commodityDto.getQuantityWrittenOff());
                    commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
                    commodityStoreUpDownDto.setRecoveryPrice(commodityDto.getRecoveryPrice());
                    commodityStoreUpDownDto.setCostPrice(commodityDto.getCostPrice());
                    commodityStoreUpDownDto.setRetailVIPPrice(commodityDto.getRetailVIPPrice());
                    commodityStoreUpDownService.insert(commodityStoreUpDownDto);
                }
            }
            //修改
        } else {
            ServerResponse byIdCommodityVo = findByIdCommodityVo(commodityDto);
            CommodityVo commodityVo = (CommodityVo) byIdCommodityVo.getData();
            Boolean flog = this.compareParams(commodityVo, commodityDto);
            if (flog) {
                return ServerResponse.createBySuccess();
            }
            //修改商品
            commodityDto.setCommodityGroupId(commodityDto.getCommodityGroups().getId());//商品分组id
            //开启兑换 判断
            commodityDto.setOpenRecovery(this.isOpenRecovery(commodityDto));
            //开启回收 判断
            commodityDto.setOpenExchange(this.isOpenExchange(commodityDto));
            commodityDao.updateCommodity(commodityDto);

            //没填写商品条码 生成条码
            if (commodityDto.getBarCode().isEmpty() && commodityDto.getBarCodeStatus()) {
                Long barCode = commodityDto.getId();
                // 补齐5位数，不足的前面用0填充
                String sb = commodityDto.getCommodityGroupId() + String.format("%05d", barCode);
                // 将拼接好的字符串赋值给商品的barCode属性
                commodityDto.setBarCode(sb);
                //更新barCode 商品条码
                commodityDao.updateCommodity(commodityDto);
            }

            //添加操作 商品详情图片

            CommodityDetailDto commodityDetailDto = new CommodityDetailDto();
            commodityDetailDto.setCommodityId(commodityDto.getId());
            commodityDetailDto.setFileName(commodityDto.getCommodityDetailFileName());
            CommodityDetailVo commodityDetailVo = commodityDetailService.findCommodityDetailByCommodityId(commodityDetailDto);
            if(commodityDetailVo == null){
                commodityDetailService.insert(commodityDetailDto);
            }else {
                commodityDetailService.update(commodityDetailDto);
            }


            //查询原有的门店
            CommodityStoreUpDownDto coupDto = new CommodityStoreUpDownDto();
            coupDto.setUserInfo(commodityDto.getUserInfo());
            coupDto.setCommodityId(commodityDto.getId());
            List<CommodityStoreUpDownVo> haramenList = commodityStoreUpDownService.findByIdAndUserId(coupDto);

            //根据商品id修改库存成本价
            CommodityStock commodityStock = new CommodityStock();
            commodityStock.setCommodityId(commodityDto.getId());
            commodityStock.setCostPrice(commodityDto.getCostPrice());
            commodityStockService.updateByCommodityId(commodityStock);

            CommodityStoreUpDownDto removeStoreDto = new CommodityStoreUpDownDto();
            removeStoreDto.setUserInfo(commodityDto.getUserInfo());
            haramenList.forEach(c -> {
                //下架门店
                if (commodityDto.getMerchantStoreIdList() == null
                        || commodityDto.getMerchantStoreIdList().stream()
                        .noneMatch(m -> c.getMerchantStoreId().equals(m) && c.getStatus() == 1)) {
                    removeStoreDto.setStatus(CommodityStoreUpDownEnum.OFF_SHELF.getCode());
                    removeStoreDto.setId(c.getId());
                    commodityStoreUpDownService.update(removeStoreDto);
                }
            });
            if (!ObjectUtils.isEmpty(commodityDto.getMerchantStoreIdList())) {
                //过滤掉下架门店
                List<CommodityStoreUpDownVo> haramenList2 = haramenList;
                List<CommodityStoreUpDownVo> statusList = haramenList2.stream().filter(person -> person.getStatus() != 0).collect(Collectors.toList());
                log.info("过滤掉下架门店：" + JSON.toJSONString(statusList));
                for (Integer merchantStoreId : commodityDto.getMerchantStoreIdList()) {
                    int index = -1;
                    for (int i = 0; i < statusList.size(); i++) {
                        if (merchantStoreId.equals(statusList.get(i).getMerchantStoreId())) {
                            index = i;
                            break;
                        }
                    }
                    CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
                    commodityStoreUpDownDto.setUserInfo(commodityDto.getUserInfo());
                    commodityStoreUpDownDto.setCommodityId(commodityDto.getId());
                    commodityStoreUpDownDto.setMerchantStoreId(merchantStoreId);
                    commodityStoreUpDownDto.setUserId(commodityDto.getUserId());
                    commodityStoreUpDownDto.setRetailPrice(commodityDto.getRetailPrice());
                    commodityStoreUpDownDto.setIncludeCoinSalesTurnover(commodityDto.getIncludeCoinSalesTurnover());
                    commodityStoreUpDownDto.setStrictInventoryManagement(commodityDto.getStrictInventoryManagement());
                    commodityStoreUpDownDto.setOpenExchange(commodityDto.getOpenExchange());
                    commodityStoreUpDownDto.setIntegralConversionPrice(commodityDto.getIntegralConversionPrice());
                    commodityStoreUpDownDto.setLotteryConversionPrice(commodityDto.getLotteryConversionPrice());
                    commodityStoreUpDownDto.setCoinConversionPrice(commodityDto.getCoinConversionPrice());
                    commodityStoreUpDownDto.setPosTerminal(commodityDto.getPosTerminal());
                    commodityStoreUpDownDto.setIntegralMallTerminal(commodityDto.getIntegralMallTerminal());
                    commodityStoreUpDownDto.setOpenRecovery(commodityDto.getOpenRecovery());
                    commodityStoreUpDownDto.setIsSelfMention(commodityDto.getIsSelfMention());
                    commodityStoreUpDownDto.setIsDirectMail(commodityDto.getIsDirectMail());
                    commodityStoreUpDownDto.setEverydayQuantityWrittenOff(commodityDto.getEverydayQuantityWrittenOff());
                    commodityStoreUpDownDto.setQuantityWrittenOff(commodityDto.getQuantityWrittenOff());
                    commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
                    commodityStoreUpDownDto.setRecoveryPrice(commodityDto.getRecoveryPrice());
                    commodityStoreUpDownDto.setCostPrice(commodityDto.getCostPrice());
                    commodityStoreUpDownDto.setRetailVIPPrice(commodityDto.getRetailVIPPrice());
                    if (index == -1) {
                        commodityStoreUpDownService.insert(commodityStoreUpDownDto);
                    } else {
                        CommodityStoreUpDownVo commodityStoreUpDownVo = statusList.get(index);
                        commodityStoreUpDownDto.setId(commodityStoreUpDownVo.getId());
                        commodityStoreUpDownService.update(commodityStoreUpDownDto);
                    }
                }
            }

        }

        return ServerResponse.createBySuccess();
    }

    private Boolean compareParams(CommodityVo commodityVo, CommodityDto commodityDto) {
        log.info("原来数据：" + JSON.toJSONString(commodityVo));
        log.info("准备修改的数据：" + JSON.toJSONString(commodityDto));
        log.info("原来的场地集合：" + commodityVo.getCommodityStoreUpDownList().size());
        log.info("修改的场地集合：" + commodityDto.getMerchantStoreIdList().size());
        /**
         * false数据不一样 （可以修改），true数据一样（不可以修改）
         * 两者一样时候包括null （true）
         * 本来数据某一个不为null，修改的参数时候为null  （false）
         * 本来数据某一个为null 修改的参数时候不为null （false）
         * 判断两者是不一样，要提前判断两者都不能为空 （false）
         * 判断场地选中的列表：
         *  1.两个场地的列表长度不一样 （false)
         *  2.两个场地的列表长度一样并且选中的场地不一样 （false)
         * */
        //检验的时候等于false的时候就不在校验了
        Boolean flog = false;
        //商品名称
        if (!commodityVo.getName().equals(commodityDto.getName())) {
            return flog;
        }
        //条形码
        if (
                (!StringUtils.isEmpty(commodityVo.getBarCode()) && StringUtils.isEmpty(commodityDto.getBarCode())) ||
                        (StringUtils.isEmpty(commodityVo.getBarCode()) && !StringUtils.isEmpty(commodityDto.getBarCode())) ||
                        !StringUtils.isEmpty(commodityVo.getBarCode()) && !StringUtils.isEmpty(commodityDto.getBarCode()) &&
                                !commodityVo.getBarCode().equals(commodityDto.getBarCode())
        ) {
            return flog;
        }

        //商品分组
        if (commodityVo.getCommodityGroupId().compareTo(commodityDto.getCommodityGroupId()) != 0) {
            return flog;
        }
        //图片
        if (
                (!StringUtils.isEmpty(commodityVo.getFileName()) && StringUtils.isEmpty(commodityDto.getFileName())) ||
                        (StringUtils.isEmpty(commodityVo.getFileName()) && !StringUtils.isEmpty(commodityDto.getFileName())) ||
                        !StringUtils.isEmpty(commodityVo.getFileName()) && !StringUtils.isEmpty(commodityDto.getFileName()) &&
                                !commodityVo.getFileName().equals(commodityDto.getFileName())
        ) {
            return flog;
        }
        //详细图片
        if (
                (!StringUtils.isEmpty(commodityVo.getCommodityDetailFileName()) && StringUtils.isEmpty(commodityDto.getCommodityDetailFileName())) ||
                        (StringUtils.isEmpty(commodityVo.getCommodityDetailFileName()) && !StringUtils.isEmpty(commodityDto.getCommodityDetailFileName())) ||
                        !StringUtils.isEmpty(commodityVo.getCommodityDetailFileName()) && !StringUtils.isEmpty(commodityDto.getCommodityDetailFileName()) &&
                                !commodityVo.getCommodityDetailFileName().equals(commodityDto.getCommodityDetailFileName())
        ) {
            return flog;
        }
        //商品规格
        if (
                (!StringUtils.isEmpty(commodityVo.getSpec()) && StringUtils.isEmpty(commodityDto.getSpec())) ||
                        (StringUtils.isEmpty(commodityVo.getSpec()) && !StringUtils.isEmpty(commodityDto.getSpec())) ||
                        !StringUtils.isEmpty(commodityVo.getSpec()) && !StringUtils.isEmpty(commodityDto.getSpec()) &&
                                !commodityVo.getSpec().equals(commodityDto.getSpec())
        ) {
            return flog;
        }
        //描述
        if (
                (!StringUtils.isEmpty(commodityVo.getDesc()) && StringUtils.isEmpty(commodityDto.getDesc())) ||
                        (StringUtils.isEmpty(commodityVo.getDesc()) && !StringUtils.isEmpty(commodityDto.getDesc())) ||
                        !StringUtils.isEmpty(commodityVo.getDesc()) && !StringUtils.isEmpty(commodityDto.getDesc()) &&
                                !commodityVo.getDesc().equals(commodityDto.getDesc())
        ) {
            return flog;
        }

        //默认售价
        if (commodityVo.getRetailPrice().compareTo(commodityDto.getRetailPrice()) != 0) {
            return flog;
        }

        //成本价格
        if (
                (!StringUtils.isEmpty(commodityVo.getCostPrice()) && StringUtils.isEmpty(commodityDto.getCostPrice())) ||
                        (StringUtils.isEmpty(commodityVo.getCostPrice()) && !StringUtils.isEmpty(commodityDto.getCostPrice())) ||
                        !StringUtils.isEmpty(commodityVo.getCostPrice()) && !StringUtils.isEmpty(commodityDto.getCostPrice()) &&
                                commodityVo.getCostPrice().compareTo(commodityDto.getCostPrice()) != 0
        ) {
            return flog;
        }

        //会员售价
        if (
                (!StringUtils.isEmpty(commodityVo.getRetailVIPPrice()) && StringUtils.isEmpty(commodityDto.getRetailVIPPrice())) ||
                        (StringUtils.isEmpty(commodityVo.getRetailVIPPrice()) && !StringUtils.isEmpty(commodityDto.getRetailVIPPrice())) ||
                        !StringUtils.isEmpty(commodityVo.getRetailVIPPrice()) && !StringUtils.isEmpty(commodityDto.getRetailVIPPrice()) &&
                                commodityVo.getRetailVIPPrice().compareTo(commodityDto.getRetailVIPPrice()) != 0
        ) {
            return flog;
        }


        //开启库存预警
        if (
                (!StringUtils.isEmpty(commodityVo.getStrictInventoryManagement()) && StringUtils.isEmpty(commodityDto.getStrictInventoryManagement())) ||
                        (StringUtils.isEmpty(commodityVo.getStrictInventoryManagement()) && !StringUtils.isEmpty(commodityDto.getStrictInventoryManagement())) ||
                        !StringUtils.isEmpty(commodityVo.getStrictInventoryManagement()) && !StringUtils.isEmpty(commodityDto.getStrictInventoryManagement()) &&
                                commodityVo.getStrictInventoryManagement().compareTo(commodityDto.getStrictInventoryManagement()) != 0) {
            return flog;
        }

        //纳入售币营业额
        if (
                (!StringUtils.isEmpty(commodityVo.getIncludeCoinSalesTurnover()) && StringUtils.isEmpty(commodityDto.getIncludeCoinSalesTurnover())) ||
                        (StringUtils.isEmpty(commodityVo.getIncludeCoinSalesTurnover()) && !StringUtils.isEmpty(commodityDto.getIncludeCoinSalesTurnover())) ||
                        !StringUtils.isEmpty(commodityVo.getIncludeCoinSalesTurnover()) && !StringUtils.isEmpty(commodityDto.getIncludeCoinSalesTurnover()) &&
                                commodityVo.getIncludeCoinSalesTurnover().compareTo(commodityDto.getIncludeCoinSalesTurnover()) != 0) {
            return flog;
        }

        //开启兑换
        if (
                (!StringUtils.isEmpty(commodityVo.getOpenExchange()) && StringUtils.isEmpty(commodityDto.getOpenExchange())) ||
                        (StringUtils.isEmpty(commodityVo.getOpenExchange()) && !StringUtils.isEmpty(commodityDto.getOpenExchange())) ||
                        !StringUtils.isEmpty(commodityVo.getOpenExchange()) && !StringUtils.isEmpty(commodityDto.getOpenExchange()) &&
                                commodityVo.getOpenExchange().compareTo(commodityDto.getOpenExchange()) != 0) {
            return flog;
        }

        //积分兑换
        if (
                (!StringUtils.isEmpty(commodityVo.getIntegralConversionPrice()) && StringUtils.isEmpty(commodityDto.getIntegralConversionPrice())) ||
                        (StringUtils.isEmpty(commodityVo.getIntegralConversionPrice()) && !StringUtils.isEmpty(commodityDto.getIntegralConversionPrice())) ||
                        !StringUtils.isEmpty(commodityVo.getIntegralConversionPrice()) && !StringUtils.isEmpty(commodityDto.getIntegralConversionPrice()) &&
                                !commodityVo.getIntegralConversionPrice().equals(commodityDto.getIntegralConversionPrice())
        ) {
            return flog;
        }
        //彩票兑换
        if (
                (!StringUtils.isEmpty(commodityVo.getLotteryConversionPrice()) && StringUtils.isEmpty(commodityDto.getLotteryConversionPrice())) ||
                        (StringUtils.isEmpty(commodityVo.getLotteryConversionPrice()) && !StringUtils.isEmpty(commodityDto.getLotteryConversionPrice())) ||
                        !StringUtils.isEmpty(commodityVo.getLotteryConversionPrice()) && !StringUtils.isEmpty(commodityDto.getLotteryConversionPrice()) &&
                                !commodityVo.getLotteryConversionPrice().equals(commodityDto.getLotteryConversionPrice())
        ) {
            return flog;
        }
        //游戏币兑换
        if (
                (!StringUtils.isEmpty(commodityVo.getCoinConversionPrice()) && StringUtils.isEmpty(commodityDto.getCoinConversionPrice())) ||
                        (StringUtils.isEmpty(commodityVo.getCoinConversionPrice()) && !StringUtils.isEmpty(commodityDto.getCoinConversionPrice())) ||
                        !StringUtils.isEmpty(commodityVo.getCoinConversionPrice()) && !StringUtils.isEmpty(commodityDto.getCoinConversionPrice()) &&
                                !commodityVo.getCoinConversionPrice().equals(commodityDto.getCoinConversionPrice())
        ) {
            return flog;
        }
        //开启回收
        if (
                (!StringUtils.isEmpty(commodityVo.getOpenRecovery()) && StringUtils.isEmpty(commodityDto.getOpenRecovery())) ||
                        (StringUtils.isEmpty(commodityVo.getOpenRecovery()) && !StringUtils.isEmpty(commodityDto.getOpenRecovery())) ||
                        !StringUtils.isEmpty(commodityVo.getOpenRecovery()) && !StringUtils.isEmpty(commodityDto.getOpenRecovery()) &&
                                commodityVo.getOpenRecovery().compareTo(commodityDto.getOpenRecovery()) != 0) {
            return flog;
        }
        //开启回收价格
        if (
                (!StringUtils.isEmpty(commodityVo.getRecoveryPrice()) && StringUtils.isEmpty(commodityDto.getRecoveryPrice())) ||
                        (StringUtils.isEmpty(commodityVo.getRecoveryPrice()) && !StringUtils.isEmpty(commodityDto.getRecoveryPrice())) ||
                        !StringUtils.isEmpty(commodityVo.getRecoveryPrice()) && !StringUtils.isEmpty(commodityDto.getRecoveryPrice()) &&
                                !commodityVo.getRecoveryPrice().equals(commodityDto.getRecoveryPrice())
        ) {
            return flog;
        }
        //上架收银系统
        if (
                (!StringUtils.isEmpty(commodityVo.getPosTerminal()) && StringUtils.isEmpty(commodityDto.getPosTerminal())) ||
                        (StringUtils.isEmpty(commodityVo.getPosTerminal()) && !StringUtils.isEmpty(commodityDto.getPosTerminal())) ||
                        !StringUtils.isEmpty(commodityVo.getPosTerminal()) && !StringUtils.isEmpty(commodityDto.getPosTerminal()) &&
                                commodityVo.getPosTerminal().compareTo(commodityDto.getPosTerminal()) != 0) {
            return flog;
        }
        //上架小程序积分商城
        if (
                (!StringUtils.isEmpty(commodityVo.getIntegralMallTerminal()) && StringUtils.isEmpty(commodityDto.getIntegralMallTerminal())) ||
                        (StringUtils.isEmpty(commodityVo.getIntegralMallTerminal()) && !StringUtils.isEmpty(commodityDto.getIntegralMallTerminal())) ||
                        !StringUtils.isEmpty(commodityVo.getIntegralMallTerminal()) && !StringUtils.isEmpty(commodityDto.getIntegralMallTerminal()) &&
                                commodityVo.getIntegralMallTerminal().compareTo(commodityDto.getIntegralMallTerminal()) != 0) {
            return flog;
        }
        //到店自提
        if (
                (!StringUtils.isEmpty(commodityVo.getIsSelfMention()) && StringUtils.isEmpty(commodityDto.getIsSelfMention())) ||
                        (StringUtils.isEmpty(commodityVo.getIsSelfMention()) && !StringUtils.isEmpty(commodityDto.getIsSelfMention())) ||
                        !StringUtils.isEmpty(commodityVo.getIsSelfMention()) && !StringUtils.isEmpty(commodityDto.getIsSelfMention()) &&
                                commodityVo.getIsSelfMention().compareTo(commodityDto.getIsSelfMention()) != 0) {
            return flog;
        }
        //快递包邮
        if (
                (!StringUtils.isEmpty(commodityVo.getIsDirectMail()) && StringUtils.isEmpty(commodityDto.getIsDirectMail())) ||
                        (StringUtils.isEmpty(commodityVo.getIsDirectMail()) && !StringUtils.isEmpty(commodityDto.getIsDirectMail())) ||
                        !StringUtils.isEmpty(commodityVo.getIsDirectMail()) && !StringUtils.isEmpty(commodityDto.getIsDirectMail()) &&
                                commodityVo.getIsDirectMail().compareTo(commodityDto.getIsDirectMail()) != 0) {
            return flog;
        }
        //选中的场地
        if (commodityVo.getCommodityStoreUpDownList().size() != commodityDto.getMerchantStoreIdList().size()) {
            return flog;
        }
        if (commodityVo.getCommodityStoreUpDownList().size() == commodityDto.getMerchantStoreIdList().size()) {
            List<Integer> AnB = commodityDto.getMerchantStoreIdList().stream().filter(item ->
                    commodityVo.getCommodityStoreUpDownList().stream()
                            .map(CommodityStoreUpDownVo::getMerchantStoreId)
                            .collect(Collectors.toList()).contains(item)

            ).collect(Collectors.toList());
            log.info("andB" + AnB);
            if (AnB.size() != commodityVo.getCommodityStoreUpDownList().size()) {
                return flog;
            }
        }
        return true;
    }


    /**
     * 如果开启了兑换,判断彩票 积分 游戏币是否都为空或0 是则返回false
     */
    public boolean isOpenExchange(CommodityDto commodityDto) {
        if (!StringUtils.isEmpty(commodityDto.getOpenExchange()) && !commodityDto.getOpenExchange()) {
            return false;
        }
        return Optional.ofNullable(commodityDto.getIntegralConversionPrice()).orElse(0) > 0 ||
                Optional.ofNullable(commodityDto.getCoinConversionPrice()).orElse(0) > 0 ||
                Optional.ofNullable(commodityDto.getLotteryConversionPrice()).orElse(0) > 0;
    }

    /**
     * 如果开启了积分回收,判断积分价格是否为空或0 是则返回false
     */
    public boolean isOpenRecovery(CommodityDto commodityDto) {
        if (!StringUtils.isEmpty(commodityDto.getOpenRecovery()) && !commodityDto.getOpenRecovery()) {
            return false;
        }
        return Optional.ofNullable(commodityDto.getRecoveryPrice()).orElse(0) > 0;
    }

    @Override
    public ServerResponse findByGroup(CommodityDto commodityDto) {

        return ServerResponse.createBySuccess(commodityDao.findByGroup(commodityDto));
    }

    @Override
    public ServerResponse findByIdCommodityVo(CommodityDto commodityDto) {
        if (StringUtils.isEmpty(commodityDto.getId())) {
            return ServerResponse.createByErrorMessage("ID不能为空");
        }

        CommodityDto commodityDtoCondition = new CommodityDto();
        commodityDtoCondition.setId(commodityDto.getId());
        commodityDtoCondition.setUserInfo(commodityDto.getUserInfo());
        Commodity commodity = commodityDao.findOneCommodityByIdAndPermission(commodityDtoCondition);

        if (StringUtils.isEmpty(commodity)) {
            return ServerResponse.createByErrorMessage("商品不存在或没权限");
        }

        CommodityVo commodityVo = new CommodityVo();
        BeanUtils.copyProperties(commodity, commodityVo);

        // 查出该商品的关联游玩项目
        List<CommodityProjectRelevanceVo> commodityProjectRelevanceVoList = commodityProjectRelevanceService.findCommodityProjectRelevanceByCommodityId(commodity.getId());
        if (StringUtils.isEmpty(commodityProjectRelevanceVoList)) {
            commodityVo.setCheckPlayList(new ArrayList<>());
        } else {
            commodityVo.setCheckPlayList(commodityProjectRelevanceVoList);
        }

        // 属于哪个分组
        CommodityGroupDto commodityGroupDto = new CommodityGroupDto();
        commodityGroupDto.setId(commodity.getCommodityGroupId());
        CommodityGroup commodityGroup = commodityGroupService.findOneCommodityGroupByCondition(commodityGroupDto);
        commodityVo.setCommodityGroup(commodityGroup);

        // 查询商品的详细照片
        CommodityDetailDto commodityDetailDto = new CommodityDetailDto();
        commodityDetailDto.setCommodityId(commodity.getId());
        CommodityDetailVo commodityDetailVo = commodityDetailService.findCommodityDetailByCommodityId(commodityDetailDto);
        if(commodityDetailVo != null){
            commodityVo.setCommodityDetailFileName(commodityDetailVo.getFileName());
        }

        // 属于哪个套票类型
        String ticketPackageType = TicketPackageTypeEnum.getTicketPackageTypeDesc(commodity.getTicketPackageType());
        commodityVo.setTicketPackageTypeName(ticketPackageType);


        // 查询上架
        CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
        commodityStoreUpDownDto.setCommodityId(commodity.getId());
        commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
        commodityStoreUpDownDto.setUserInfo(commodityDto.getUserInfo());
        List<CommodityStoreUpDownVo> commodityStoreUpDownVoList = commodityStoreUpDownService.finAllCommodityStoreUpDownByPermission(commodityStoreUpDownDto);

        commodityStoreUpDownVoList.forEach(commodityStoreUpDownVo -> {
            commodityStoreUpDownVo.setTicketPackageTypeName(TicketPackageTypeEnum.getTicketPackageTypeDesc(commodityStoreUpDownVo.getTicketPackageType()));
        });


        commodityVo.setCommodityStoreUpDownList(commodityStoreUpDownVoList);
        return ServerResponse.createBySuccess(commodityVo);
    }

    @Override
    public int insert(Commodity commodity) {
        return commodityDao.insert(commodity);
    }

    @Override
    public long calculateExpirationDays(CommodityDto commodityDto) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = null;
        if (!commodityDto.getTicketPackageType().equals(TicketPackageTypeEnum.UNDATED.getCode())) {
            if (commodityDto.getTicketPackageType().equals(TicketPackageTypeEnum.WEEK.getCode())) {
                localDateTime = DateTimeUtils.plusWeeks(commodityDto.getAmount());
            } else if (commodityDto.getTicketPackageType().equals(TicketPackageTypeEnum.MONTH.getCode())) {
                localDateTime = DateTimeUtils.plusMonths(commodityDto.getAmount());
            } else if (commodityDto.getTicketPackageType().equals(TicketPackageTypeEnum.SEASON.getCode())) {
                localDateTime = DateTimeUtils.plusMonths(commodityDto.getAmount() * 3);
            } else if (commodityDto.getTicketPackageType().equals(TicketPackageTypeEnum.YEAR.getCode())) {
                localDateTime = DateTimeUtils.plusYears(commodityDto.getAmount());
            } else if (commodityDto.getTicketPackageType().equals(TicketPackageTypeEnum.CUSTOMIZE.getCode())) {
                localDateTime = DateTimeUtils.plusDays(commodityDto.getAmount());
            }
            if (!ObjectUtils.isEmpty(localDateTime)) {
                return DateTimeUtils.periodDays(now, localDateTime);
            }
        }
        return 0;
    }

    @Override
    public List<CommodityVo> findAllCommodity(CommodityDto commodityDto) {
        commodityDto.setType(CommodityTypeEnum.CURRENT.getCode());
        return commodityDao.findAllCommodity(commodityDto);
    }

    @Override
    public Commodity findOneCommodityByIdAndPermission(CommodityDto commodityCondition) {

        return commodityDao.findOneCommodityByIdAndPermission(commodityCondition);
    }

    @Override
    public ServerResponse findAllCommodityPage(CommodityDto commodityDto) {
        PageHelper.startPage(commodityDto.getPageNum(), commodityDto.getPageSize());
        if (StringUtils.isEmpty(commodityDto.getType())) {
            commodityDto.setType(CommodityTypeEnum.CURRENT.getCode());
        }
        List<CommodityVo> commodityVoList = commodityDao.findAllCommodity(commodityDto);
        PageInfo pagResult = new PageInfo(commodityVoList);
        return ServerResponse.createBySuccess(pagResult);
    }

    /**
     * 添加编辑售货机私人商品管理
     */
    @Override
    public ServerResponse editVendingMachineGoods(CommodityDto commodityDto) {
        if (StringUtils.isEmpty(commodityDto.getRetailPrice())) {
            return ServerResponse.createByErrorMessage("参考售价不能为空");
        }
        if (StringUtils.isEmpty(commodityDto.getCostPrice())) {
            return ServerResponse.createByErrorMessage("成本价不能为空");
        }
        if (StringUtils.isEmpty(commodityDto.getFileName())) {
            return ServerResponse.createByErrorMessage("商品图片不能为空");
        }
        Commodity commodity = new Commodity();
        Integer count;
        if (StringUtils.isEmpty(commodityDto.getId())) {
            commodity.setUserId(commodityDto.getUserId());
            commodity.setCommodityGroupId(commodityDto.getCommodityGroup().getId());
            commodity.setType(CommodityTypeEnum.CURRENT.getCode());
            commodity.setRetailPrice(commodityDto.getRetailPrice());
            commodity.setStrictInventoryManagement(true);
            commodity.setName(commodityDto.getName());
            commodity.setCostPrice(commodityDto.getCostPrice());
            commodity.setSpec(commodityDto.getSpec());
            commodity.setBarCode(commodityDto.getBarCode());
            commodity.setFileName(commodityDto.getFileName());
            commodity.setClientTerminal(true);
            count = commodityDao.insert(commodity);

            CommodityDetailDto commodityDetailDto = new CommodityDetailDto();
            commodityDetailDto.setCommodityId(commodity.getId());
            commodityDetailDto.setFileName(commodityDto.getCommodityDetailFileName());
            commodityDetailService.insert(commodityDetailDto);

        } else {
            // 查询商品是否存在
            CommodityVo commodityVo = commodityDao.findCommodityById(commodityDto);
            if (StringUtils.isEmpty(commodityVo)) {
                return ServerResponse.createByErrorMessage("当前商品信息有误，编辑失败");
            }
            if (!StringUtils.isEmpty(commodityDto.getCommodityGroup())) {
                commodity.setCommodityGroupId(commodityDto.getCommodityGroup().getId());
            }
            commodity.setUserId(commodityDto.getUserId());
            commodity.setId(commodityDto.getId());
            commodity.setRetailPrice(commodityDto.getRetailPrice());
            commodity.setName(commodityDto.getName());
            commodity.setCostPrice(commodityDto.getCostPrice());
            commodity.setSpec(commodityDto.getSpec());
            commodity.setBarCode(commodityDto.getBarCode());
            commodity.setFileName(commodityDto.getFileName());
            count = commodityDao.updateVendingMachineCommodity(commodity);

            //添加操作 商品详情图片
            CommodityDetailDto commodityDetailDto = new CommodityDetailDto();
            commodityDetailDto.setCommodityId(commodityDto.getId());
            commodityDetailDto.setFileName(commodityDto.getCommodityDetailFileName());
            CommodityDetailVo commodityDetailVo = commodityDetailService.findCommodityDetailByCommodityId(commodityDetailDto);
            if(commodityDetailVo == null){
                commodityDetailService.insert(commodityDetailDto);
            }else {
                commodityDetailService.update(commodityDetailDto);
            }
            try {
                if (count > 0 && !StringUtils.isEmpty(commodityVo.getFileName()) && !commodityVo.getFileName().equals(commodityDto.getFileName())) {
                    uploadService.deleteByFileNameToFTP(commodityVo.getFileName());
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("售货机删除旧图片失败:{}", e.getMessage());
            }

        }

        if (count > 0) {
            return ServerResponse.createBySuccess();
        } else {
            return ServerResponse.createByErrorMessage("添加商品失败，请联系平台处理");
        }

    }

    @Override
    public ServerResponse findCommodityById(CommodityDto commodityDto) {
        CommodityVo commodityVo = commodityDao.findCommodityById(commodityDto);
        if (commodityVo != null) {
            CommodityDetailDto commodityDetailDto = new CommodityDetailDto();
            commodityDetailDto.setCommodityId(commodityVo.getId());
            CommodityDetailVo commodityDetailVo = commodityDetailService.findCommodityDetailByCommodityId(commodityDetailDto);
            if(commodityDetailVo != null){
                commodityVo.setCommodityDetailFileName(commodityDetailVo.getFileName());
            }
        }
        return ServerResponse.createBySuccess(commodityVo);
    }

    @Override
    public List<CommodityInfoCommonVo> findCommodityByBarCode(String barCode) {
        return commodityDao.findCommodityByBarCode(barCode);
    }

    /**
     * 根据条形码和userId查询商品信息
     */
    @Override
    public List<CommodityInfoCommonVo> findCommodityByBarCodeAndUserId(String barCode, Integer userId) {
        // 先查当前账号的商品commodity表，如果没有就调用调用查询商品公共表commodity_info_common
        List<CommodityInfoCommonVo> list = commodityDao.findCommodityByBarCodeAndUserId(barCode, userId);
        if (list.size() == 0) {
            CommodityInfoCommon commodityInfoCommon = new CommodityInfoCommon();
            commodityInfoCommon.setBarCode(barCode);
            CommodityInfoCommonVo commodityInfoCommonVo = commodityInfoCommonDao.findOneCommodityInfoCommon(commodityInfoCommon);
            if (!ObjectUtils.isEmpty(commodityInfoCommonVo)) {
                list.add(commodityInfoCommonVo);
            }
        }
        return list;
    }

    @Override
    public ServerResponse findCommodityList(CommodityDto commodityDto) {

        commodityDto.setCommodityStoreStatus(CommodityStoreUpDownEnum.GROUNDING.getCode());
        commodityDto.setDeleteStatus(false);
        PageHelper.startPage(commodityDto.getPageNum(), commodityDto.getPageSize());
        if (StringUtils.isEmpty(commodityDto.getType()) || !StringUtils.isEmpty(commodityDto.getBranchType())) {
            commodityDto.setType(CommodityTypeEnum.CURRENT.getCode());
        }
        List<CommodityVo> commodityVoList;
        if (StringUtils.isEmpty(commodityDto.getBranchType())) {
            commodityVoList = commodityDao.findCommodityList(commodityDto);
        } else {
            //售货机查询商品，不连接上下架表
            commodityVoList = commodityDao.findSalesCommodityList(commodityDto);
        }
        PageInfo pagResult = new PageInfo(commodityVoList);
        return ServerResponse.createBySuccess(pagResult);
    }

    @Override
    public void commodityOffTheShelves(CommodityDto commodityDto) {
        commodityDao.updateOffTheShelvesById(commodityDto.getCommodityId(), commodityDto.getUserId(), true);
        //售货机，不修改上下架表
        if (StringUtils.isEmpty(commodityDto.getBranchType())) {
            CommodityStoreUpDownDto commodityStoreUpDownDto = new CommodityStoreUpDownDto();
            commodityStoreUpDownDto.setStatus(CommodityStoreUpDownEnum.OFF_SHELF.getCode());
            commodityStoreUpDownDto.setCommodityId(commodityDto.getCommodityId());
            commodityStoreUpDownDto.setUserId(commodityDto.getUserId());
            commodityStoreUpDownService.updateOffTheShelvesById(commodityStoreUpDownDto);
        }
    }


    @Override
    public CommodityVo queryById(Long id) {
        return commodityDao.queryById(id);
    }

}
